package array;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class SpiralMatrix54 {
    @Test
    public void test() {
        spiralOrder(new int[][]{new int[]{1,2,3}, new int[]{4,5,6}, new int[]{7,8,9}});
        spiralOrder(new int[][]{new int[]{1,2,3}});
        spiralOrder(new int[][]{new int[]{1}, new int[]{2}, new int[]{3}});
    }
    public List<Integer> spiralOrder(int[][] m) {
        List<Integer> result = new ArrayList<>(m.length * m[0].length);
        int x1 = 0;
        int x2 = m.length-1;
        int y1 = 0;
        int y2 = m[0].length-1;
        while (x1 <= x2 && y1 <= y2) {
            visitRectangleBorder(m, result, x1, x2, y1, y2);
            x1++;
            x2--;
            y1++;
            y2--;
        }
        System.out.println(result);
        return result;
    }

    public void visitRectangleBorder(int[][] m, List<Integer> result,
                                     int x1, int x2, int y1, int y2) {
        for (int y = y1; y <= y2; y++) {
            result.add(m[x1][y]);
        }
        for (int x = x1+1; x <= x2; x++) {
            result.add(m[x][y2]);
        }
        if (x1 < x2) {
            for (int y = y2 - 1; y >= y1; y--) {
                result.add(m[x2][y]);
            }
        }
        if (y1 < y2) {
            for (int x = x2 - 1; x > x1; x--) {
                result.add(m[x][y1]);
            }
        }
    }
}
